const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, extractNumber, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')


router.get('/', authenticateToken, async (req, res) => {
    try {
        const { project_name, category_id, status } = req.query;

        let sql = 'SELECT p.*, pc.category_name FROM project p LEFT JOIN project_category pc ON p.category_id = pc.category_id WHERE 1=1';
        let params = [];

        // 模糊查询项目名称
        if (project_name && project_name.trim()) {
            sql += ' AND p.project_name LIKE ?';
            params.push(`%${project_name.trim()}%`);
        }

        // 按分类筛选
        if (category_id && category_id.trim()) {
            sql += ' AND p.category_id = ?';
            params.push(category_id.trim());
        }

        // 按创建时间排序
        sql += ' ORDER BY p.create_time DESC';

        // 添加调试信息
        console.log('🔍 查询参数:', { project_name, category_id, status });
        console.log('🔍 最终SQL:', sql);
        console.log('🔍 SQL参数:', params);

        const [result] = await db.execute(sql, params);

        result.forEach(item => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss');
            if (item.update_time) {
                item.update_time = dayjs(item.update_time).format('YYYY-MM-DD HH:mm:ss');
            }
        });

        await logUserOperation(req, '查询', '获取项目', '获取项目成功', '成功');
        res.json({
            success: true,
            message: '获取项目成功',
            data: result,
            total: result.length
        });
    } catch (error) {
        console.error('获取项目失败:', error);
        await logUserOperation(req, '查询', '获取项目', '获取项目失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取项目失败',
            error: error.message
        });
    }
});

// 新增项目分类
// {"project_name":"爱仕达多","category_id":"TY00002","description":"描述","price":"123","materials":""}
router.put('/add', authenticateToken, async (req, res) => {
    try {
        const { project_name, category_id, description, price, materials } = req.body;

        // 参数验证
        if (!project_name || !project_name.trim()) {
            return res.status(400).json({
                success: false,
                message: '分类名称不能为空'
            });
        }

        if (!category_id || !category_id.trim()) {
            return res.status(400).json({
                success: false,
                message: '分类类型不能为空'
            });
        }

        if (!description || !description.trim()) {
            return res.status(400).json({
                success: false,
                message: '描述不能为空'
            });
        }

        if (!price) {
            return res.status(400).json({
                success: false,
                message: '价格不能为空'
            });
        }


        // 获取数据库中最大的category_id TY00001
        const [maxProjectId] = await db.execute(
            'SELECT MAX(project_id) AS max_project_id FROM project'
        );
        let nextId = 1;

        if (maxProjectId[0].max_project_id) {
            // 提取数字部分并加1
            const currentNumber = extractNumber(maxProjectId[0].max_project_id);
            nextId = currentNumber + 1;
        }

        const project_id = generateString('PR', nextId, 5);
        const create_time = dayjs().format('YYYY-MM-DD HH:mm:ss');

        let sql = `INSERT INTO project (project_id, project_name, category_id, description, price, materials, create_time) VALUES (?, ?, ?, ?, ?, ?, ?)`;
        let params = [project_id, project_name.trim(), category_id.trim(), description.trim(), price, materials.trim(), create_time];

        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '添加', '新增项目', '新增项目成功', '成功');
        res.json({
            success: true,
            message: '新增项目成功',
            data: {
                project_id,
                project_name: project_name.trim(),
                category_id: category_id.trim(),
                description: description.trim(),
                price: price,
                materials: materials.trim(),
                create_time,
            }
        });
    } catch (error) {
        console.error('新增项目失败:', error);
        await logUserOperation(req, '添加', '新增项目', '新增项目失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '新增项目失败',
            error: error.message
        });
    }
});

// 更新项目
router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { project_id, project_name, category_id, description, price, materials } = req.body;

        // 参数验证
        if (!project_name || !project_name.trim()) {
            return res.status(400).json({
                success: false,
                message: '分类名称不能为空'
            });
        }

        if (!category_id || !category_id.trim()) {
            return res.status(400).json({
                success: false,
                message: '分类类型不能为空'
            });
        }

        if (!description || !description.trim()) {
            return res.status(400).json({
                success: false,
                message: '描述不能为空'
            });
        }

        if (!price) {
            return res.status(400).json({
                success: false,
                message: '价格不能为空'
            });
        }


        let sql = `UPDATE project SET project_name = ?, category_id = ?, description = ?, price = ?, materials = ? WHERE project_id = ?`;
        let params = [project_name.trim(), category_id.trim(), description.trim(), price, materials.trim(), project_id];

        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '更新', '更新项目', '更新项目成功', '成功');
        if (result.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                message: '更新失败，分类不存在'
            });
        }

        await logUserOperation(req, '更新', '更新项目', '更新项目失败', '失败', '更新失败，分类不存在');
        res.json({
            success: true,
            message: '更新项目成功',
            data: {
                project_id,
                project_name: project_name.trim(),
                category_id: category_id.trim(),
                description: description.trim(),
                price: price,
                materials: materials.trim()
            }
        });
    } catch (error) {
        console.error('更新项目失败:', error);
        await logUserOperation(req, '更新', '更新项目', '更新项目失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '更新项目失败',
            error: error.message
        });
    }
});

// 删除项目分类
router.delete('/delete', authenticateToken, async (req, res) => {
    try {
        console.log('删除请求参数:', req.query);
        const { project_id } = req.query;

        // 参数验证
        if (!project_id) {
            return res.status(400).json({
                success: false,
                message: '分类ID不能为空'
            });
        }

        // 检查分类是否存在
        const [existingCategory] = await db.execute(
            'SELECT project_id, project_name FROM project WHERE project_id = ?',
            [project_id]
        );

        if (existingCategory.length === 0) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }

        let sql = `DELETE FROM project WHERE project_id = ?`;
        let params = [project_id];

        const [result] = await db.execute(sql, params);

        if (result.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                message: '删除失败，分类不存在'
            });
        }

        await logUserOperation(req, '删除', '删除项目', '删除项目成功', '成功');
        res.json({
            success: true,
            message: '删除项目成功',
            data: {
                project_id,
                project_name: existingCategory[0].project_name,
                deleted: true
            }
        });
    } catch (error) {
        console.error('删除项目失败:', error);
        await logUserOperation(req, '删除', '删除项目', '删除项目失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '删除项目失败',
            error: error.message
        });
    }
});

// 获取项目分类
router.get('/project_category', authenticateToken, async (req, res) => {
    try {
        let sql = 'SELECT * FROM project_category';
        let [result] = await db.execute(sql);
        result = result.map(item => {
            return {
                category_id: item.category_id,
                category_name: item.category_type
            }
        });
        res.json({
            success: true,
            message: '获取项目分类成功',
            data: result
        });
    } catch (error) {
        console.error('获取项目分类失败:', error);
        res.status(500).json({
            success: false,
            message: '获取项目分类失败',
            error: error.message
        });
    }
});

module.exports = router;